import express from "express"
//如果以前引入过模块,那么他再次引入,其实是引入的缓存
//始终是1次,因为前面引入过了
import multer from "multer";
import DB from "./../../libs/DBHelper"
import fs from "fs";

//图片上传
var multerObj = multer({
    dest: "/upload"
})

//创建保安
let apiRouter = express.Router();


//注册时判断用户名是否存在
apiRouter.get("/checkuser", async function (request, response, next) {
    //sql语句
    let checkSql = "SELECT uname FROM `usersinfo` WHERE uname=?"
    //前端发来的数据
    let params = [request.query.uname]
    //DB查询
    let res = await DB.execAsync(checkSql, params)
    console.log(res)
    if (res.length >= 1) {
        response.send("false")
    } else {
        response.send("true")
    }
})


//登录
apiRouter.post("/login", (request, response, next) => {

    if (request.body.uphone) {
        var userData = [request.body.uphone]
        var loginSql = "select `u_id`,`uname`,`uphone`,`utype`,`uemail` from `usersinfo` where uphone=?"


        DB.exec(loginSql, userData, function (err, row, fields) {
            if (err) {
                response.json({
                    msg: err.message,
                    status: -5
                })
            }
            if (row.length >= 1) {
                //存入session里
                request.session["isLogin"] = row[0]
                response.json({
                    msg: "登录成功",
                    status: 1,
                    data: row[0]
                })
            } else {
                response.json({
                    msg: "登录失败",
                    status: -1
                })
            }
        })

    } else {
        var userData = [request.body.uname, request.body.upwd]

        //登录sql语句
        var loginSql = "select `u_id`,`uname`,`uphone`,`utype`,`uemail` from `usersinfo` where uname=? and upwd=?"

        DB.exec(loginSql, userData, function (err, row, fields) {
            if (err) {
                response.json({
                    msg: err.message,
                    status: -5
                })
            }
            if (row.length >= 1) {
                request.session["isLogin"] = row[0]
                response.json({
                    msg: "登录成功",
                    status: 1,
                    data: row[0]
                })
            } else {
                response.json({
                    msg: "登录失败",
                    status: -1
                })
            }
        })
    }
})

//注册
apiRouter.post("/reg", async (request, response, next) => {

    let regSql = 'INSERT INTO `usersinfo` (`uname`,`upwd`,`uphone`)VALUES(?,?,?)';
    let params = [request.body.uname, request.body.upwd, request.body.uphone];

    let res = await DB.execAsync(regSql, params)

    console.log(res.affectedRows)

    try {
        if (res.affectedRows) {
            response.json({
                msg: "注册成功",
                status: 2
            })
        } else {
            response.json({
                msg: "注册失败",
                status: -2
            })
        }
    } catch (error) {
        response.json({
            msg: "注册异常",
            status: -3
        })
    }
})



//商品列表
apiRouter.get("/goods", (request, response, next) => {
    let goodStr = fs.readFileSync("data/list.json").toString();
    response.json({
        data: goodStr
    })
})

//每个商品
apiRouter.get("/goodsInfo/:id", (request, response, next) => {
    let goodStr = fs.readFileSync("data/list.json").toString();
    let goodsObj = JSON.parse(goodStr).filter(function (el, index) {
        return el.p_id == request.params.id
    })
    response.json(goodsObj)
})

//加入购物车
apiRouter.get("/addCart", async (request, response, next) => {
    let addCartSql = "SELECT * FROM `cart` WHERE `u_id`=? AND `p_id`=? AND `c_color`=? AND `c_size`=? AND `c_status`=1"
    let pramsArr = [
        request.query.uid,
        request.query.pid,
        request.query.ccolor,
        request.query.csize
    ]
    let res = await DB.execAsync(addCartSql, pramsArr);
    if (res.length >= 1) {
        //以前有购买过,加数量就可以了
        let yeSql = "UPDATE `cart` SET `c_num`=`c_num`+? WHERE`u_id`=? AND `p_id`=? AND `c_size`=?  AND `c_color`=? AND `c_status`=1"
        let pramsArr3 = [
            request.query.cnum,
            request.query.uid,
            request.query.pid,
            request.query.csize,
            request.query.ccolor
        ]
        let res3 = await DB.execAsync(yeSql, pramsArr3);

        if (res3.affectedRows) {
            response.json({
                msg: "加入购物车成功*",
                status: 6
            })
        } else {
            response.json({
                msg: "加入购物车失败*",
                status: -6
            })
        }
    } else {
        //以前没有购买过,加入购物车
        let NoBuySql = "INSERT INTO `cart` (`p_id`,`u_id`,`c_name`,`c_img`,`c_color`,`c_size`,`c_price`,`c_num`)VALUES(?,?,?,?,?,?,?,?)"
        let pramsArr2 = [
            request.query.pid,
            request.query.uid,
            request.query.cname,
            request.query.cimg,
            request.query.ccolor,
            request.query.csize,
            request.query.cprice,
            request.query.cnum
        ]
        let res2 = await DB.execAsync(NoBuySql, pramsArr2);
        if (res2.affectedRows) {
            response.json({
                msg: "加入购物车成功",
                status: 4
            })
        } else {
            response.json({
                msg: "加入购物车失败",
                status: -4
            })
        }
    }
})

//获取购物车
apiRouter.get("/getCart", async (request, response, next) => {
    let getSql = "SELECT `p_id`,`u_id`,`c_name`,`c_img`,`c_color`,`c_size`,`c_price`,`c_num`,`c_id` FROM `cart` WHERE `u_id`=? AND `c_status`=1"
    let getPrams = [
        request.query.uid
    ]

    let res = await DB.execAsync(getSql, getPrams);
    if (res.length >= 1) {
        response.json({
            msg: "获取购物车成功",
            status: 7,
            data: JSON.stringify(res)
        })
    } else {
        response.json({
            msg: "获取购物车失败",
            status: -7
        })
    }
})

//修改购物
apiRouter.get("/modify", async (request, response, next) => {
    let modiSql = "UPDATE `cart` SET `c_num`=? WHERE`u_id`=? AND `p_id`=? AND `c_size`=?  AND `c_color`=?  AND `c_status`=1";
    let modiPrams = [
        request.query.cnum,
        request.query.uid,
        request.query.pid,
        request.query.csize,
        request.query.ccolor,
    ]
    let res = await DB.execAsync(modiSql, modiPrams)
    console.log(res)
    if (res.affectedRows >= 1) {
        response.json({
            msg: "修改成功",
            status: 8
        })
    } else {
        response.json({
            msg: "修改失败",
            status: -8,
        })
    }
})

//删除购物车
apiRouter.get("/delete", async (request, response, next) => {
    let deleSql = "UPDATE `cart` SET `c_status`=0 WHERE `c_id`=? ;";
    let delePrams = [
        request.query.cid,
    ]
    let res = await DB.execAsync(deleSql, delePrams)
    console.log(res)
    if (res.affectedRows >= 1) {
        response.json({
            msg: "删除成功",
            status: 9
        })
    } else {
        response.json({
            msg: "删除失败",
            status: -9,
        })
    }
})

//图片上传
apiRouter.post("/upload", multerObj.any(), (request, response, next) => {
    response.end("ok")
})

//暴露保安大爷去干活
module.exports = {
    apiRouter
}

//图片上传专用接口
// server.post("/api/upload", multerObj.any(), function (request, response, next) {

//     // var upload = request.files[0]
//     // let ext = path.extname(upload.originalname)
//     // fs.rename(upload.path, upload.path + ext, function (err, status) {
//     //     if (err) {
//     //         response.json({
//     //             msg: "图片上传失败",
//     //             status: -5
//     //         })
//     //     } else {
//     //         response.json({
//     //             msg: "图片上传成功",
//     //             status: 5
//     //         })
//     //     }

//     // })

//     response.end("ok")

// })
